package com.fengzheng.basic.common.config.authorization.login;

import cn.hutool.json.JSONUtil;
import com.fengzheng.basic.common.config.response.ResultBean;
import com.fengzheng.basic.common.config.response.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liht
 * @date 2022/3/25 2:21 下午
 */
@Slf4j
@Component
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse httpServletResponse, AuthenticationException exception) throws IOException, ServletException {
        log.info("登入失败");
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
//        httpServletResponse.getWriter().print(JSONUtil.toJsonStr(new ResultBean<>(BaseErrorCode.NOT_PERMISSION)));

//        httpServletResponse.getWriter().print(JSONUtil.parseObj(new ResultBean<>(BaseErrorCode.LOGIN_FAIL),false));

        httpServletResponse.getWriter().print(JSONUtil.parseObj(new ResultBean<>(new ServiceException(exception.getMessage())),false));

        httpServletResponse.flushBuffer();
    }

}
